/*
 * author      : 吴中勤 
 * date        : 2018/12/21
 * description : TODO
 */

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibExample {

    // 被代理的类, 没有接口
    static class Hello {
        void sayHi() {
            System.out.println("hi");
        }
    }

    // cglib动态代理类, 方法会被转发到 intercept
    // 对被代理的对象一无所知
    static class HelloMethodInterceptor implements MethodInterceptor{

        public Object getInstance(Class clazz) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(clazz);
            enhancer.setCallback(this);
            return enhancer.create();
        }

        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            System.out.println("before");
            Object result = proxy.invokeSuper(obj, args);
            System.out.println("after");
            return result;
        }
    }

    public static void main(String[] args) {
        HelloMethodInterceptor interceptor = new HelloMethodInterceptor();
        Hello hello = (Hello) interceptor.getInstance(Hello.class);
        hello.sayHi();
    }
}
